<!--
@Description:客户管理
@Author:zqy
@Date:2022-10-21 14:31:27
@Last Modified by:zqy
@Last Modified time:2022-10-21 14:31:27
-->
<template>
  <div class="bg_gray">
    <ComHeader title="客户管理" bg-color="#FFFFFF" :arrow="false" :border="false" title-left @get-height="handleHeadHeight" />
    <div class="customer-page-search">
      <SearchInput v-model="searchValue" :icon-right="true" @search="handleSearch" />
    </div>
    <CustomerNavFilter @change="handleChangeNav">
      <List
        ref="list"
        component-name="CustomerNavFilter"
        :class="{'c-list-scroll':list.length>0}"
        :finished.sync="finished"
        :reset-fun="resetData"
        :load="load"
        :refresh="load"
        :default-active="true"
      >
        <Item
          v-for="(c,i) in list"
          :key="i"
          :customer-type="customerType"
          :common-status="commonStatus"
          :item-data="c"
          :follow-up-types="CRM_FOLLOW_UP_TYPE"
        />
      </List>
    </CustomerNavFilter>
    <Tabbar :customer-type="customerType" @change-customer="handleChangeCustomerType" />
  </div>
</template>
<script>
import Tabbar from '@/components/Tabbar'
import SearchInput from '@/components/SearchInput'
import CustomerNavFilter from './components/NavFilter'
import List from '@/components/List'
import Item from './components/Item'
import { bus } from '@/utils/bus'
import { getCustomerList, getDisDetail, distributorConfigCategoryByDisCode } from '@/apis/customer'
import { getDictByPatchType } from '@/apis/dataDict'
export default {
  name: 'CustomerHome',
  components: {
    Tabbar, CustomerNavFilter, SearchInput, List, Item
  },
  data() {
    return {
      headHeight: 50,
      searchValue: '',
      customerType: 0, // 客户类型：0 公告客户池  1 潜客 2 意向客户
      commonStatus: 0, // 公共客户池状态: 1 待分配 2 已分配  3 无效/流失客户
      dictData: {}, // 数据字典

      filtersRaw: [], // filter查询条件
      paramsRaw: {}, // param查询参数
      sortersRaw: [], // sort组合排序
      list: [],
      finished: false, // 列表是否加载完成
      isRefreshPage: false, // 是否在激活状态刷新分页接口
      createCustomerType: 0 // 创建客户时的客户类型：1 潜客，2 意向客户
    }
  },
  computed: {
    // 默认查询配置条件
    defaultQueryConfig() {
      const otherFilters = []
      const params = {}
      const sorters = [
        { id: 'filingTime', property: 'filingTime', direction: 'DESC' }
        // { id: 'createTime', property: 'createTime', direction: 'DESC' }
        //  TODO:20230713 将排序暂时处理为按照 filingTime 降序，其他排序方式后续待定
      ] // 排序
      if (this.customerType === 0) {
        // 公告客户池
        if (this.commonStatus === 1) {
          // 待分配
          // 展示新/退标识的列表 排序按 新倒序、退倒序、建档时间倒序 排列
          otherFilters.push({ id: 'clueCustomerType', property: 'clueCustomerType', value: 'FailureCustomer', operator: '<>' })
          params.queryWaitDistributing = 1
          /* sorters = [
            { id: 'isNewDis', property: 'isNewDis', direction: 'DESC' },
            { id: 'isFollowReturn', property: 'isFollowReturn', direction: 'DESC' },
            { id: 'filingTime', property: 'filingTime', direction: 'DESC' },
            { id: 'createTime', property: 'createTime', direction: 'DESC' }
          ] // TODO:20230713 将排序暂时处理为按照 filingTime 降序，其他排序方式后续待定*/
        } else if (this.commonStatus === 2) {
          // 已分配
          otherFilters.push({ id: 'clueCustomerType', property: 'clueCustomerType', value: 'FailureCustomer', operator: '<>' })
          params.queryHasDistributed = 1
        } else if (this.commonStatus === 3) {
          // 无效/流失
          params.queryFailureCustomer = 1
        } else {
          // 全部
          /* sorters = [
            { id: 'isNewDis', property: 'isNewDis', direction: 'DESC' },
            { id: 'isFollowReturn', property: 'isFollowReturn', direction: 'DESC' },
            { id: 'filingTime', property: 'filingTime', direction: 'DESC' },
            { id: 'createTime', property: 'createTime', direction: 'DESC' }
          ]// TODO:20230713 将排序暂时处理为按照 filingTime 降序，其他排序方式后续待定 */
        }
      } else if (this.customerType === 1) {
        // 潜客
        otherFilters.push({
          id: 'clueCustomerType',
          property: 'clueCustomerType',
          value: 'PotentialCustomer',
          operator: '='
        })
      } else if (this.customerType === 2) {
        // 意向
        otherFilters.push({
          id: 'clueCustomerType',
          property: 'clueCustomerType',
          value: '[IntentionalCustomer,DepositCustomer,OrderedCustomer]',
          operator: 'in'
        })
      }
      return {
        filtersRaw: otherFilters,
        sortersRaw: sorters,
        paramsRaw: params
      }
    },
    CRM_FOLLOW_UP_TYPE() {
      return (this.dictData && this.dictData.CRM_FOLLOW_UP_TYPE) || []
    }
  },
  created() {
    window.refreshOrderItem = ({ type, id }) => {
      this.refreshCustomerItem({ type, id })
    }
    bus.$on('refreshCustomerItem', this.refreshCustomerItem)
  },
  mounted() {

  },
  activated() {
    if (this.isRefreshPage) {
      this.$nextTick(() => {
        if (this.createCustomerType) {
          const params = {
            type: this.createCustomerType,
            status: '',
            filter: {}
          }
          this.handleChangeNav(params)
          this.createCustomerType = 0
          this.isRefreshPage = false
          return
        }
        this.resetPageData()
        this.isRefreshPage = false
      })
    }
  },
  deactivated() {

  },
  beforeRouteLeave(to, from, next) {
    if (to.path === '/purorder') {
      this.$removeKeepAliveCache(this)
    }
    next()
  },
  methods: {
    async getDictData() {
      const dictTypeCodes = ['CRM_FOLLOW_UP_TYPE']
      this.dictData = await getDictByPatchType({ dictTypeCodes })
    },
    handleHeadHeight(h) {
      this.headHeight = h
    },
    handleSearch(value) {
      this.searchValue = value.trim()
      this.$nextTick(() => {
        this.resetPageData()
      })
    },
    handleChangeNav(data) {
      this.customerType = data.type || 0
      this.commonStatus = data.status || 0
      if (data.type === -1) return
      const f = data.filter || {}
      const filterRawKeys = ['disCustomerFirstSource', 'disCustomerSecondSource', 'isFollowReturn', 'shopDeptCode', 'isEnterStore', 'clueCustomerType']
      const filterTimes = ['filingTime', 'lastFailureTime', 'lastFollowupTime']
      const filtersRaw = []
      const sortersRaw = []
      const paramsRaw = {}
      const none = [null, undefined, '']
      for (const [k, v] of Object.entries(f)) {
        if (none.includes(v) || (v instanceof Array && v.length === 0)) {
          continue
        }
        if (k === 'sortType') {
          // 排序 ： 活跃排序 lastActiveTime , 跟进排序 lastFollowupTime
          sortersRaw.push({ id: `${v}1`, property: v, direction: 'DESC' })
          continue
        }
        if (filterRawKeys.includes(k)) {
          let value = v
          if (v instanceof Array) {
            value = `[${v.join(',')}]`
          }
          filtersRaw.push({
            id: k, property: k, operator: v instanceof Array ? 'in' : '=', value: value
          })
        } else if (filterTimes.includes(k)) {
          // 时间查询
          filtersRaw.push({
            id: `${k}0`, property: k, operator: '>=', value: v[0]
          })

          filtersRaw.push({
            id: `${k}1`, property: k, operator: '<=', value: v[1]
          })
        } else {
          paramsRaw[k] = v instanceof Array ? v.join(',') : v
        }
      }
      this.filtersRaw = filtersRaw
      this.paramsRaw = paramsRaw
      this.sortersRaw = sortersRaw
      this.resetPageData()
    },
    resetPageData() {
      if (this.$refs.list) {
        this.$refs.list.resetPageData()
      }
    },
    load(page, rows) {
      const data = {
        page,
        rows,
        filtersRaw: [...this.filtersRaw, ...this.defaultQueryConfig.filtersRaw],
        paramsRaw: { ...this.defaultQueryConfig.paramsRaw, ...this.paramsRaw },
        sortersRaw: [...this.defaultQueryConfig.sortersRaw, ...this.sortersRaw]
      }

      const searchVal = `${this.searchValue || ''}`.trim()
      if (searchVal && searchVal.length > 0) {
        if (/^1[3|4|5|6|7|8|9][0-9]{9}$/.test(searchVal)) {
          data.filtersRaw.push({ id: 'phone', property: 'phone', operator: '=', value: searchVal })
        } else {
          data.paramsRaw = { ...data.paramsRaw, ...{ fuzzyKey: searchVal }}
        }
      }
      const headers = {
        'Permission-PerCode': this.customerType !== 0 ? 'my_customer_pool' : 'common_customer_pool',
        'Permission-App': 'top2-crm-app'
      }
      return getCustomerList(data, headers).then(res => {
        const records = res.data.records || []
        this.list.push(...records)
        if (this.list.length >= res.data.total) {
          this.finished = true
        }
      })
    },
    resetData() {
      this.list = [
        // { id: '1', name: '李雷', time: '2018.12.11 10:30', sex: 1, level: 1, shopDeptCode: 'BMK1002710005' },
        // { id: '2', name: '李雷', time: '2018.12.11 10:30', sex: 0, level: 2, shopDeptCode: 'BMK1002710005' },
        // { id: '3', name: '李雷', time: '2018.12.11 10:30', sex: 1, level: 3, shopDeptCode: 'BMK1002710005' },
        // { id: '4', name: '李雷', time: '2018.12.11 10:30', sex: 1, level: 4, shopDeptCode: 'BMK1002710005' }
      ]
    },
    /**
     * @param {string} type 操作类型：edit 编辑，allocation 分配，follow 跟进 ， collection 收款， refund 退款 ，turnIntention 转意向客户 ， createOpty 创建商机 ，addTag 添加标签，sendBack 退回总部，sendBackShop 退回门店 ，losing 客户流失 , feedback 自投反馈
     * @param {String} id 线索客户Id
    */
    refreshCustomerItem({ type, id }) {
      if (type === 'add') {
        // 新建：刷新操作时所停留的列表页
        this.isRefreshPage = true
        return
      }
      if (type === 'allocation') {
        // 分配: 操作后刷新所选客户所在的列表页
        this.isRefreshPage = true
        return
      }
      if (type === 'sendBackShop') {
        // 退回门店：操作后刷新所选客户所在的列表页
        this.isRefreshPage = true
        return
      }
      if (type === 'turnIntention') {
        // 转意向客户：操作后刷新所选客户所在的列表页
        this.resetPageData()
        return
      }
      if (type === 'sendBack') {
        // 退回总部：操作后刷新所选客户所在的列表页
        this.isRefreshPage = true
        return
      }
      if (type === 'losing') {
        /* // 客户流失：将数据从当前状态下移除，刷新无效客户列表
        const index = this.list.findIndex(v => v.id === id)
        if (index > -1) {
          this.list.splice(index, 1)
        } */
        // 客户流失：操作后刷新所选客户所在的列表页
        this.isRefreshPage = true
        return
      }

      const index = this.list.findIndex(v => v.id === id)
      if (index === -1) return
      this.refreshDetail(id, index)

      if (type === 'addTag') {
        // 添加标签：操作后刷新所选客户上的‘标签’信息、最新跟进记录
      }
      if (type === 'collection') {
        // 收款：刷新客户的最新跟进记录
      }
      if (type === 'createOpty') {
        // 创建商机：刷新客户的最新跟进记录、商机信息页面
      }
      if (type === 'follow') {
        // 跟进：操作新所选客户上的最新跟进记录
      }
      if (type === 'edit') {
        // 编辑：刷新操作时所停留的列表页
      }
    },
    refreshDetail(id, index) {
      const data = {
        page: 1,
        rows: 1,
        filtersRaw: [{ id: 'id0', property: 'id', operator: '=', value: id }],
        paramsRaw: {},
        sortersRaw: []
      }
      const headers = {
        'Permission-PerCode': this.customerType !== 0 ? 'my_customer_pool' : 'common_customer_pool',
        'Permission-App': 'top2-crm-app'
      }
      return getCustomerList(data, headers).then(res => {
        const records = res.data.records || []
        if (records && records.length === 1) {
          const data = records[0]
          this.$set(this.list, index, data)
        }
      })
    },
    handleChangeCustomerType(type) {
      this.createCustomerType = type
    }
  }
}
</script>
<style lang="less" scoped>
  .customer-page-search{
    position: fixed;
    top: 46px;
    left: 0;
    width: 100%;
    z-index: 999;
    background: #fff;
  }
</style>
